package com.atguigu.cloud.interceptor;

import com.atguigu.cloud.entity.po.BaseEntity;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;

import java.time.LocalDateTime;
import java.util.Properties;

/**
 * @author Jungle
 * 自动插入和更新时间
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "update",
        args = {MappedStatement.class, Object.class}
)})
public class MybatisTimeInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        Object parameter = args[1];

        String methodId = ms.getId();
        String methodName = methodId.substring(methodId.lastIndexOf(".") + 1);

        // 判断是否为插入操作，并且实体类中包含 createTime 和 updateTime 字段
        if (methodName.startsWith("insert") && parameter instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) parameter;
            LocalDateTime now = LocalDateTime.now();
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
        }

        // 如果是更新操作，并且实体类中包含 updateTime 字段
        if (methodName.startsWith("update") && parameter instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) parameter;
            entity.setUpdateTime(LocalDateTime.now());
        }

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可以在这里设置一些属性
    }
}
